package com.tonann.tonannmqtt.mqtt.mulitipleServer;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 项目启动 监听主题
 */
@Slf4j
@Component
public class MqttClientListener implements ApplicationListener<ContextRefreshedEvent> {

    private volatile AtomicBoolean isInit = new AtomicBoolean(false);

//    @Autowired
//    private IAppGatewayService gatewayService;
//
//    @Autowired
//    private IAppSensorService sensorService;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            //防止重复触发
            if (!isInit.compareAndSet(false, true)) {
                return;
            }
//            AppGateway appGateway = new AppGateway();
//            appGateway.setGatewayType("2");
//            appGateway.setStatus("0");
//            List<AppGateway> gatewayList = gatewayService.selectAppGatewayList(appGateway);
//            List<String> uris = new ArrayList<>();
//            for (AppGateway gateway : gatewayList) {
            String url = "tcp://59.110.170.159:1883";
            MqttClientConnect mqttClientConnect = new MqttClientConnect();
            mqttClientConnect.setMqttClientId("mqtt" + UUID.randomUUID());
            String host = "tcp://59.110.170.159:1883";
            mqttClientConnect.setMqttClient(host, mqttClientConnect.getMqttClientId(), null, null, false, new MqttClientCallback(mqttClientConnect.getMqttClientId()));
            mqttClientConnect.sub(StringUtils.commaDelimitedListToStringArray("#"));
            MqttClientConnect.mqttClients.put(mqttClientConnect.getMqttClientId(), mqttClientConnect);
            MqttClientConnect.mqttBrokers.put("59.110.170.159:1883", mqttClientConnect);
            log.info("{}--连接成功！！订阅主题--{}", mqttClientConnect.getMqttClientId(), "#");
//                List<AppSensor> appSensorList = sensorService.selectAppSensorListByGatewayType("2");
//                for (AppSensor sensor : appSensorList) {
//                    String tag = sensor.getMqttDeviceChannel() + "." + sensor.getMqttDeviceName() + "." + sensor.getMqttDeviceTag();
//                    MQTTSensor.getInstance().map.put(tag, sensor);
//                }
//            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

}